package org.example.order.controller;

import org.example.order.cache.OrderCacheList;
import org.example.order.domain.Order;
import org.example.order.service.IOrdersServer;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.concurrent.ExecutionException;

/**
 * 下单 Controller
 */
@Controller
public class OrdersContorller {


    @Autowired
    private IOrdersServer ordersServer;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发起一个订单
     * 将消息发送到MQ，要得到mq服务器返回的消息确认，消息才发送成功，订单创建成功
     */
    @RequestMapping("/order/create")
    public String createOrder(Model model) throws ExecutionException, InterruptedException {
        Order order = ordersServer.craeteOrder(model);
        System.out.println("开始创建一个订单：" + order.toString());

        //将消息发送到order队列
        CorrelationData correlationData = new CorrelationData();
        rabbitTemplate.convertAndSend(
                //交换机
                "ex.order",
                //routingKey
                "order.key",
                order.getOrderId(),
                correlationData
        );
        // 设置同步等待
        CorrelationData.Confirm confirm = correlationData.getFuture().get();
        // 消息是否得到broker的确认
        boolean confirmAck = confirm.isAck();
        if (!confirmAck){
            //订单创建失败
            return "failorder";
        }
        OrderCacheList.ORDER_MAP.put(order.getOrderId(), order);
        model.addAttribute("orderId",order.getOrderId());
        //下单成功跳转到支付页面
        return "pay";
    }


    /**
     * 获取订单状态
     * @param model
     * @param orderId
     * @return
     */
    @RequestMapping("/order/getOrderStatus/{orderId}")
    public String getOrderStatus(Model model,
                                 @PathVariable("orderId") Long orderId) {
        Order order = OrderCacheList.findOrderByOrderId(orderId);
        System.out.println("查询订单状态："+order);
        model.addAttribute("order", order);
        return "success";
    }

}
